package com.wolfalpha.utron.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.service.UserService;
import com.wolfalpha.utron.service.impl.UserServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by luodon on 15/8/17.
 */
public class RegisterPhone extends Fragment {
    //对父Activity的接口
    private RegisterPhoneListener mlistener;
    private EditText phone;
    private EditText code;
    private Button btnSend;

    //时间线程
    private Timer timer = new Timer();
    //倒计时60秒
    private int leftSec = 60;

    private final static int COUNT_RUN = 1;
    private final static int COUNT_OVER = 2;
    private final static int TOAST_MSG = 3;

    private CountTask countTask = null;

    private boolean Code_Sended = false;

    public android.os.Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case COUNT_OVER:
                    btnSend.setText("获取验证码");
                    btnSend.setClickable(true);
                    btnSend.invalidate();
                    //没有倒计时
                    break;
                case COUNT_RUN:
                    btnSend.setText("剩余" + msg.arg1 + "秒");
                    btnSend.setClickable(false);
                    btnSend.invalidate();
                    //正在倒计时
                    break;
                case TOAST_MSG:
                    UIHelper.ToastMessage(getActivity(), msg.obj.toString());
                    break;
            }
        }
    };

    public interface RegisterPhoneListener {
        public void onFinished(String phone);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_register_phone, container, false);

        phone = (EditText) view.findViewById(R.id.et_phone);
        code = (EditText) view.findViewById(R.id.et_code);
        btnSend = (Button) view.findViewById(R.id.btn_send);

        //发送验证码
        btnSend.setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View v) {
                                           final String phoneStr = phone.getText().toString().trim();
                                           if (!TextUtils.isEmpty(phoneStr)) {
                                               if (phoneStr.length() != 11) {
                                                   //提示框手机格式错误
                                                   toast("手机格式错误");
                                                   return;
                                               }
                                               ThreadPoolUtils.execute(new Runnable() {
                                                   @Override
                                                   public void run() {
                                                       try {
                                                           UserService userService = new UserServiceImpl();
                                                           boolean result = userService.getPhoneCode(phoneStr);
                                                           System.out.println(result);
                                                           if (!result) {
                                                               //提示框获取失败
                                                               toast("获取验证码失败，请重试");
                                                           } else {
                                                               toast("验证码已发送，请查收");
                                                               Code_Sended = true;
                                                               if (timer != null) {
                                                                   if (countTask != null) {
                                                                       countTask.cancel();
                                                                   }
                                                                   countTask = new CountTask();
                                                                   timer.schedule(countTask, 1000, 1000);
                                                               }
                                                           }
                                                       } catch (Exception e) {
                                                           e.printStackTrace();
                                                           toast("发送失败，请稍后重试");
                                                       }
                                                   }

                                               });
                                           } else {
                                               //提示框输入手机号码
                                               toast("请输入手机号码");
                                           }
                                       }
                                   }

        );

        //监听验证码输入框
        code.addTextChangedListener(new TextWatcher() {
                                        @Override
                                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                        }

                                        @Override
                                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                                            //判断当4个数字都填了后，发起验证请求
                                            if (s.length() == 4 && !TextUtils.isEmpty(phone.getText().toString().trim())) {
                                                final String phoneStr = phone.getText().toString().trim();
                                                final String codeStr = code.getText().toString().trim();
                                                ThreadPoolUtils.execute(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        try {
                                                            UserService userService = new UserServiceImpl();
                                                            boolean result = userService.checkPhoneCode(phoneStr, codeStr);

                                                            if (AppContext.getInstance().getDebug()) {
                                                                mlistener.onFinished(phoneStr);
                                                                return;
                                                            }

                                                            if (result) {
                                                                mlistener.onFinished(phoneStr);
                                                            } else {
                                                                toast("验证码错误");
                                                            }
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            }
                                        }

                                        @Override
                                        public void afterTextChanged(Editable s) {

                                        }
                                    }

        );

        return view;
    }

    public void setPhoneListener(RegisterPhoneListener listener) {
        this.mlistener = listener;
    }

    /**
     * 执行验证码重新获取的倒计时
     */
    class CountTask extends TimerTask {

        @Override
        public void run() {
            android.os.Message msg = new android.os.Message();
            if (leftSec < 0) {
                msg.what = COUNT_OVER;
                handler.sendMessage(msg);
                leftSec = 60;
                timer.cancel();
                timer = new Timer();
            } else {
                msg.what = COUNT_RUN;
                msg.arg1 = leftSec;
                handler.sendMessage(msg);
                leftSec--;
            }
        }
    }

    /**
     * Toast 消息
     *
     * @param msg
     */
    private void toast(String msg) {
        Message massage = new Message();
        massage.what = TOAST_MSG;
        massage.obj = msg;
        handler.sendMessage(massage);
    }
}
